/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.submarine.transport.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import org.submarine.common.TransferSerializable;
import org.submarine.exchange.TransferObject;

/**
 * @file org.submarine.transport.codec.NettyDecoder.java
 *
 * 解码器
 * 
 * @author gaojian
 * @created 2013-8-20 下午2:30:25
 * @version 0.0.1
 * @since 0.0.1
 * 
 */
public class NettyDecoder extends LengthFieldBasedFrameDecoder {//ByteToMessageDecoder {
	
	private String charsetName;
	
	public NettyDecoder(String charsetName) {
		super(1024 * 1024 * 8, 0, 4, 0, 4);
		this.charsetName = charsetName;
	}

	/* (non-Javadoc)
	 * @see io.netty.handler.codec.LengthFieldBasedFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf)
	 */
	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		ByteBuf byteBuf = (ByteBuf) super.decode(ctx, in);
		if (null == byteBuf) {
			return null;
		}
		
		int length = byteBuf.readInt();
		byte[] decoded = new byte[length];
		byteBuf.readBytes(decoded);
		
		return TransferSerializable.json2Obj(new String(decoded, charsetName), TransferObject.class);
	}


}